<template>
  <el-dialog
    v-model="visible"
    title="确认订单"
    width="700px"
    :before-close="handleClose"
  >
    <div class="order-confirm-content">
      <!-- 商品信息 -->
      <div class="section">
        <h4>商品信息</h4>
        <div class="products-list">
          <div v-for="item in cartItems" :key="item.id" class="product-item">
            <div class="product-image">
              <img :src="item.product?.image || '/default-product.jpg'" :alt="item.product?.name" />
            </div>
            <div class="product-info">
              <div class="product-name">{{ item.product?.name }}</div>
              <div class="product-price">¥{{ item.product?.price }} × {{ item.quantity }}</div>
            </div>
            <div class="product-subtotal">¥{{ (item.product?.price * item.quantity).toFixed(2) }}</div>
          </div>
        </div>
      </div>

      <!-- 订单金额 -->
      <div class="section">
        <h4>订单金额</h4>
        <div class="amount-info">
          <div class="amount-row">
            <span>商品总额：</span>
            <span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="amount-row">
            <span>运费：</span>
            <span>¥0.00</span>
          </div>
          <div class="amount-row total">
            <span>实付金额：</span>
            <span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmOrder" 
          :loading="creating"
          :disabled="!isAddressValid"
        >
          确认下单
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

export default {
  name: 'OrderConfirmDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    cartItems: {
      type: Array,
      default: () => []
    },
    address: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'order-created'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    });

    const creating = ref(false);
    
    const totalPrice = computed(() => {
      return props.cartItems.reduce((sum, item) => {
        return sum + (item.product?.price * item.quantity);
      }, 0);
    });

    const isAddressValid = computed(() => {
      return true; // 这里需要根据实际情况调整
    });

    const handleClose = () => {
      visible.value = false;
    };

    const confirmOrder = async () => {
      // 验证地址
      if (!isAddressValid.value) {
        ElMessage.warning('请完善收货地址信息');
        return;
      }

      creating.value = true;
      try {
        // 获取购物车商品ID列表
        const cartItemIds = props.cartItems.map(item => parseInt(item.id));
        
        console.log('创建订单请求参数:', {
          userId: localStorage.getItem('userId'),
          addressId: props.address.id,
          cartItemIds: cartItemIds
        });
        
        // 创建订单
        const response = await request.post('/orders', cartItemIds, {
          params: { 
            userId: localStorage.getItem('userId'),
            addressId: props.address.id
          }
        });
        
        if (response.code === 200) {
          ElMessage.success('订单创建成功');
          emit('order-created', response.data);
          visible.value = false;
        } else {
          ElMessage.error(response.message || '创建订单失败');
        }
      } catch (error) {
        ElMessage.error('创建订单失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        creating.value = false;
      }
    };

    return {
      visible,
      creating,
      totalPrice,
      isAddressValid,
      handleClose,
      confirmOrder
    };
  },
  watch: {
    modelValue(newVal) {
      if (newVal) {
        this.handleVisibleChange(newVal);
      }
    }
  }
};
</script>

<style scoped>
.order-confirm-content {
  max-height: 500px;
  overflow-y: auto;
}

.section {
  margin-bottom: 30px;
}

.section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.address-info {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.address-selection {
  margin-top: 15px;
}

.existing-address,
.new-address-form {
  margin-top: 15px;
}

.selected-address-info {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #d4edda;
}

.address-row {
  margin-bottom: 8px;
}

.address-row:last-child {
  margin-bottom: 0;
}

.address-row .label {
  font-weight: 600;
  color: #606266;
  margin-right: 10px;
}

.address-row .value {
  color: #303133;
}

.no-address {
  text-align: center;
  padding: 20px;
}

.products-list {
  max-height: 300px;
  overflow-y: auto;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 50px;
  height: 50px;
  margin-right: 15px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-right: 15px;
}

.product-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.product-price {
  color: #909399;
  font-size: 14px;
}

.product-subtotal {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}

.amount-info {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.amount-row:last-child {
  margin-bottom: 0;
}

.amount-row.total {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
  margin-top: 10px;
}

.dialog-footer {
  text-align: right;
}
</style> 